package handler

import (
	"github.com/gin-gonic/gin"
	"onvif_server/api"
	"onvif_server/api/subscription"
	"onvif_server/internal/errcode"
	"onvif_server/internal/service"
)

type SubscriptionHandler struct {
	*Handler
	subService service.SubscriptionService
}

func NewSubscriptionHandler(handler *Handler, subService service.SubscriptionService) *SubscriptionHandler {
	return &SubscriptionHandler{
		Handler:    handler,
		subService: subService,
	}
}

func (h *SubscriptionHandler) List(ctx *gin.Context) {
	req := subscription.ListReq{}
	if err := ctx.ShouldBind(&req); err != nil {
		api.Fail(ctx, errcode.ErrInvalidParams.Wrap(err))
		return
	}
	total, items, err := h.subService.List(ctx, &req)
	api.PageData(ctx, total, items, err)
}

func (h *SubscriptionHandler) Create(ctx *gin.Context) {
	req := subscription.CreateReq{}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		api.Fail(ctx, errcode.ErrInvalidParams.Wrap(err))
		return
	}
	api.Response(ctx, h.subService.Create(ctx, &req), nil)
}

func (h *SubscriptionHandler) Update(ctx *gin.Context) {
	req := subscription.UpdateReq{}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		api.Fail(ctx, errcode.ErrInvalidParams.Wrap(err))
		return
	}
	api.Response(ctx, h.subService.Update(ctx, &req), nil)
}

func (h *SubscriptionHandler) Delete(ctx *gin.Context) {
	req := subscription.DeleteReq{}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		api.Fail(ctx, errcode.ErrInvalidParams.Wrap(err))
		return
	}
	api.Response(ctx, h.subService.Delete(ctx, req.IDs), nil)
}

func (h *SubscriptionHandler) Topics(ctx *gin.Context) {
	api.Success(ctx, h.subService.Topics(ctx))
}

func (h *SubscriptionHandler) Test(ctx *gin.Context) {
	req := subscription.TestReq{}
	if err := ctx.ShouldBind(&req); err != nil {
		api.Fail(ctx, errcode.ErrInvalidParams.Wrap(err))
		return
	}
	err := h.subService.Test(ctx, &req)
	api.Response(ctx, err, nil)
}
